import { UploadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { useSetState } from 'ahooks';
import { Button, Card, Upload } from 'antd';
import SparkMD5 from 'spark-md5';

import { postBaseUploadChunk, postGoCaptchaData } from '@/services/index';

const HomePage: React.FC = () => {
  const { name } = useModel('global');
  const [state, setState] = useSetState({
    tb64: '',
    b64: '',
  });

  const propsUpload = {
    showUploadList: false,
    beforeUpload: async (file) => {
      const isImage =
        ['image/png', 'image/jpeg', 'image/webp'].indexOf(file.type) !== -1;
      // if (!isImage) {
      //   message.error('不是图片');
      //   return;
      // }

      // 100k
      const level = checkLevel(file.size / 1024);
      const listBlob = chunks(file, level * 1024);
      const fileMd5 = await hashFile(listBlob);
      console.log({ fileMd5, listBlob, level });

      onPostBaseUploadChunk({
        index: 0,
        listBlob,
        fileMd5,
        file,
      });
      return false;
    },
  };

  const checkLevel = (num) => {
    let str = parseInt(num).toString().length;
    if (str === 1) return 1;
    if (str === 2) return 10;
    if (str === 3) return 100;
    if (str === 4) return 1000;
    if (str === 5) return 10000;
    return 100000;
  };

  function chunks(file, chunkSize) {
    const list = [];
    for (let i = 0; i < file.size; i += chunkSize) {
      list.push(file.slice(i, i + chunkSize));
    }
    return list;
  }

  function hashFile(chunks) {
    return new Promise((resolve) => {
      const spark = new SparkMD5();
      function _read(i) {
        if (i >= chunks.length) {
          resolve(spark.end());
          return;
        }
        const index = chunks[i];
        const reader = new FileReader();
        reader.onload = (e) => {
          const bytes = e.target.result; // 读取到的字节数
          spark.append(bytes);
          _read(i + 1);
        };
        reader.readAsArrayBuffer(index);
      }
      _read(0);
    });
  }

  const onPostBaseUploadChunk = async (data) => {
    const req = {
      chunk_index: data.index,
      chunk_blob: data.listBlob[data.index],
      chunk_total: data.listBlob.length,
      file_name: data.file.name.split('.').pop(),
      file_size: data.file.size,
      file_md5: data.fileMd5,
    };
    const [err, res] = await postBaseUploadChunk(req);
    console.log({ err, res });
    if (err) {
      return;
    }
    // 秒传
    if (res.image) {
      return;
    }
    // 分片
    data.index += 1;
    if (data.index < data.listBlob.length) {
      onPostBaseUploadChunk(data);
    }
  };

  // 验证码
  const onpostGoCaptchaData = async () => {
    const req = {
      dots: '131',
      Key: '131',
    };
    const [err, res] = await postGoCaptchaData(req);
    console.log({ err, res });
    if (err) {
      return;
    }
    setState({
      b64: res.b64,
      tb64: res.tb64,
    });
  };

  return (
    <PageContainer ghost>
      <div className="flex">
        <Card title="大文件上传" style={{ width: 300 }} className="mr-2">
          <Upload {...propsUpload}>
            <Button icon={<UploadOutlined />}>Click to Upload</Button>
          </Upload>
        </Card>

        <Card title="验证码" style={{ width: 300 }} className="mr-2">
          <Button
            onClick={() => {
              onpostGoCaptchaData();
            }}
          >
            验证码
          </Button>
          <div>
            <img src={state.tb64}></img>
            <img src={state.b64}></img>
          </div>
        </Card>
      </div>
    </PageContainer>
  );
};

export default HomePage;
